package org.i1510.common.utils.file;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.KBProperties;
public class FileUtils {

	protected static Log logger = LogFactory.getLog(DateUtils.class);
	private static  int  inputMax = KBProperties.INPUTMAX;
	/**
	*@author Kenshinbo@163.com
	*@描述：String转化成输入字节流
	*@param str
	*@return
	*@throws UnsupportedEncodingException 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:03:24 PM KB
	*/
	public static InputStream stringToInputStream(String str)
			throws UnsupportedEncodingException {
		ByteArrayInputStream stream = new ByteArrayInputStream(str
				.getBytes("UTF-8"));
		return stream;
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：文件转化成文本输出
	*@param fileName
	*@param charSet
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:05:34 PM KB
	*/
	public static String fileToString(String fileName, String charSet) throws Exception {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream(fileName), charSet));
		String line = null;
		while ((line = br.readLine()) != null) {
			sb.append(line+"\n");
		}
		return sb.toString();
	}

	/**
	*@author Kenshinbo@163.com
	*@描述：读取远程文件
	*@param url
	*@param path
	*@return 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:09:08 PM KB
	*/
	public static boolean readUrlFile(String url, String path) {
		try {
			URL currentUrl = new URL(url);
			URLConnection conn = currentUrl.openConnection();
			conn.connect();
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			if (httpConn.getResponseCode() == 200) {
				logger.info("不能连接：" + currentUrl+ " 返回代码：" + httpConn.getResponseCode());
				return false;
			}
			File file = createFile(conn.getInputStream(), path);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：从流中创建文件
	*@param stream
	*@param fileName
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:11:19 PM KB
	*/
	public static File createFile(InputStream stream, String fileName)throws Exception {
		File newFile = new File(fileName);
		OutputStream fileOut = new BufferedOutputStream(new FileOutputStream(
				newFile));
		byte[] buffer = new byte[inputMax];//使用1024字节传输
		int bytesRead = 0;		
		while ((bytesRead = stream.read(buffer, 0, inputMax)) != -1) {
			fileOut.write(buffer, 0, bytesRead);
		}
		
		fileOut.close();
		stream.close();
		
		return newFile;
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：目录拷贝
	*@param sourcedir
	*@param destdir
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:45:52 PM KB
	*/
	public static boolean copyDir(String sourcedir, String destdir)throws Exception {
		boolean tage = false;
		File dest = new File(destdir);
		File source = new File(sourcedir);
		String files[] = source.list();
		try {
			createDir(destdir);
		} catch (Exception ex) {
			return false;
		}
		for (int i = 0; i < files.length; i++) {
			String sourcefile = source + File.separator + files[i];
			String destfile = dest + File.separator + files[i];
			File temp = new File(sourcefile);
			if (temp.isFile()) {
				try {
					copy(sourcefile, destfile);
				} catch (Exception ex) {
					return false;
				}
			}
		}
		return true;
	
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：创建目录
	*@param dir
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:40:07 PM KB
	*/
	public static void createDir(String dir) throws Exception {
		File dirTemp = new File(dir);
		if (!dirTemp.exists()) {
			try {
				dirTemp.mkdirs();
			} catch (Exception ex) {
				throw new Exception("不能创建目录 :" + dir);
			}
		}
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：通过流拷贝
	*@param input
	*@param output
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:47:19 PM KB
	*/
	public static boolean copy(String input, String output) throws Exception {		
		FileInputStream fis = new FileInputStream(input);
		FileOutputStream fos = new FileOutputStream(output);
		try {
			byte buf[] = new byte[inputMax];
			int i;
			while ((i = fis.read(buf)) > -1) {
				fos.write(buf, 0, i);
			}
		} catch (Exception ex) {
			throw new Exception("Copy失败：" + ex.getMessage());
		} finally {
			fis.close();
			fos.close();
		}
		return true;
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：创建文件 
	*@param output 文件路径(文件不存在则自动创建) PS:目录不存在则会创建失败！
	*@param content 文件内容
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 3:51:19 PM KB
	*/
	public static void createFile(String output, String content)throws Exception {
		try {
			OutputStreamWriter fw = new OutputStreamWriter(
					new FileOutputStream(output));
			PrintWriter out = new PrintWriter(fw);
			out.print(content);
			out.close();
			fw.close();
		} catch (Exception ex) {
			throw new Exception(ex);
		}
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：删除文件
	*@param filename
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 4:25:03 PM KB
	*/
	public static boolean deleteFile(String filename) throws Exception {
		File file = new File(filename);

		return deleteFile(file);
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：删除文件对象
	*@param file
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 4:25:15 PM KB
	*/
	public static boolean deleteFile(File file) throws Exception {
		if (file.isDirectory()) {
			return deleteDir(file);
		}

		if (!file.exists()) {
			return false;
		}

		return file.delete();
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：删除目录下的全部
	*@param dir
	*@return
	*@throws Exception 
	*@version  FileUtils.java,v 1.1 Dec 28, 2010 4:25:40 PM KB
	*/
	public static boolean deleteDir(File dir) throws Exception {
		if (dir.isFile()) {
			deleteFile(dir);
		}

		File[] files = dir.listFiles();

		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				File file = files[i];

				if (file.isFile()) {
					file.delete();
				} else {
					deleteDir(file);
				}
			}
		}

		return dir.delete();
	}
	  /** 
     * 创建查询指定目录下文件的方法 
     *  
     * @param allList 
     *            指定目录 
     * @param endName 
     *            指定以“”结尾的文件 
     * @return 得到的文件数目 
     */   
    public static int findTxtFileCount(File allList,String endName){   
       //   
       int textCount=0;   
    // 创建fileArray名字的数组  
    File[] fileArray= allList.listFiles();   
    // 如果传进来一个以文件作为对象的allList 返回0  
    if(null==fileArray){   
         return 0;   
        }   
    // 偏历目录下的文件  
    for(int i=0;i<fileArray.length;i++){   
       // 如果是个目录  
           if(fileArray[i].isDirectory()){   
         // System.out.println("目录: "+fileArray[i].getAbsolutePath());  
            // 递归调用  
            textCount+=findTxtFileCount(fileArray[i].getAbsoluteFile(),endName);   
         // 如果是文件  
          }else if(fileArray[i].isFile()){   
         // 如果是以“”结尾的文件  
         if(fileArray[i].getName().endsWith(endName)){   
            // 展示文件  
            System.out.println("exe文件: "+fileArray[i].getAbsolutePath());   
            // 所有以“”结尾的文件相加  
            textCount++;   
         }   
         }   
    }   
    return textCount;   
  
    }   
        
       /** 
        * 获取文件 
        * 可以根据正则表达式查找 
        * @param dir String 文件夹名称 
        * @param s String 查找文件名，可带*.?进行模糊查询 
        * @return File[] 找到的文件 
        */  
       public static File[] getFiles(String dir,String s) {  
         //开始的文件夹  
         File file = new File(dir);  
  
         s = s.replace('.', '#');  
         s = s.replaceAll("#", "\\\\.");  
         s = s.replace('*', '#');  
         s = s.replaceAll("#", ".*");  
         s = s.replace('?', '#');  
         s = s.replaceAll("#", ".?");  
         s = "^" + s + "$";  
  
//         System.out.println(s);  
         Pattern p = Pattern.compile(s);  
         
         ArrayList list = filePattern(file, p);  
  
         File[] rtn = new File[list.size()];  
         list.toArray(rtn);  
         return rtn;  
       }  
  
       /** 
        * @param file File 起始文件夹 
        * @param p Pattern 匹配类型 
        * @return ArrayList 其文件夹下的文件夹 
        */  
  
       private static ArrayList filePattern(File file, Pattern p) {  
         if (file == null) {  
           return null;  
         }  
         else if (file.isFile()) {  
           Matcher fMatcher = p.matcher(file.getName());  
           if (fMatcher.matches()) {  
             ArrayList list = new ArrayList();  
             list.add(file);  
             return list;  
           }  
         }  
         else if (file.isDirectory()) {  
           File[] files = file.listFiles();  
           if (files != null && files.length > 0) {  
             ArrayList list = new ArrayList();  
             for (int i = 0; i < files.length; i++) {  
               ArrayList rlist = filePattern(files[i], p);  
               if (rlist != null) {  
                 list.addAll(rlist);  
               }  
             }  
             return list;  
           }  
         }  
         return null;  
       }  
       /**
    *@Author Rambo
    *@Desc：拷贝文件
    *@param readfile
    *@param writeFile TODO
    *@Version  FileUtils.java,v 1.1 2014-9-16 上午12:29:52 
    */
    public static void copy2(String readfile,String writeFile) {
    	    try {
    	        FileInputStream input = new FileInputStream(readfile);
    	        FileOutputStream output = new FileOutputStream(writeFile);
    	        int read = input.read();       
    	        while ( read != -1 ) {
    	            output.write(read);
    	            read = input.read();
    	        }          
    	        input.close();
    	        output.close();
    	    } catch (IOException e) {
    	        System.out.println(e);
    	    }
    	}
	public static void main(String[] args) {
		try {
			createFile("D:\\MyShow\\com.uzg.backContrlPlatForm\\WebRoot\\code\\show.txt","ssss");
//			copyDir("D:\\MyShow\\com.uzg.backContrlPlatForm\\WebRoot\\code","D:\\MyShow\\com.uzg.backContrlPlatForm\\WebRoot\\code1");
//			deleteFile("D:\\MyShow\\com.uzg.backContrlPlatForm\\WebRoot\\code\\show.txt");
//			File[] files = getFiles("D:\\MyShow\\com.uzg.backContrlPlatForm\\WebRoot\\code\\","sh*.txt");
//			System.out.println(files.length);
		
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
